import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import routes from './router';
import login from './router/login';
import store from './store';
import plugin from './common/plugin/index';
// import './windowResize'
import {storageLocal} from '@/common/utils/storage';
import {getLoginInfo} from '@/api/user';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import './style/index.less';
import {filterMenu, getButtons} from '@/common/utils/menu';

// 使用ElementUI
Vue.use(ElementUI);
Vue.use(plugin);
Vue.use(VueRouter);

function render(route) {
    // 定义路由
    const router = new VueRouter({
        mode: process.env.NODE_ENV === 'development' ? 'hash' : 'history',
        base: '',
        routes: route,
    });
    
    // 渲染app
    const app = new Vue({
        el: '#app',
        router,
        store,
        render: h => h(App),
    });
    return router;
}

const noAuthRoute = [
    ...login,
    {
        path: '*',
        redirect: '/login',
    },
];

let token = storageLocal.get('token');
if (/login/.test(location.href) || !token) {
    store.dispatch('initStates');
    render(noAuthRoute);
} else {
    let roleId = storageLocal.get('role');
    getLoginInfo({roleId}).then(({data}) => {
        if (!data) {
            throw '';
        }
        const {mainMenus, roleList, user, currentRole} = data;
        const {id, userName, realName} = user;
        store.commit('setUser', {id, userName, realName});
        store.commit('setRoles', roleList);
        if (!roleId) {
            roleId = currentRole.id;
            storageLocal.set('role', roleId);
        }
        // 超级管理员-1
        let showMenu = roleId === -1 ? routes : filterMenu(routes, mainMenus);
        // let showMenu = routes;
        store.commit('setMenus', showMenu);
        const buttons = getButtons(mainMenus);
        store.commit('setButtons', buttons);
        render(routes);
    }).catch(err => {
        console.log(err);
        store.dispatch('initStates');
        const router = render(noAuthRoute);
        router.push({name: 'login'});
    });
    // let showMenu = routes;
    // store.commit('setUser', {});
    // store.commit('setMenus', showMenu);
    // render(showMenu);
}
